import {sendRequest} from '@/util/api.js'
class websocketUtil {
	constructor(url, time) {
		this.is_open_socket = false //避免重复连接
		this.url = url //地址
		this.data = null
		//心跳检测
		this.timeout = time //多少秒执行检测
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectTimeOut = null //重连之后多久再次重连
		this.msgData = null
		try {
			return this.connectSocketInit()
		} catch (e) {
			console.log('catch');
			this.is_open_socket = false
			this.reconnect();
		}
	}

	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		this.socketTask = uni.connectSocket({ 
			url: this.url,
			success: () => {
				//用户登录成功，加载消息缓存
				uni.getStorage({
					key:'chatList'+uni.getStorageSync('uuId'),
					success(res) {
						let list = res.data;
						if(list.length != 0){
							getApp().globalData.chatList = list;
							console.log(JSON.stringify(getApp().globalData.chatList)+'-------------------');
						}
					}
				});
				console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常！");
			//连接打开，查询是否有未读消息
			this.unreadData();
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(this.heartbeatInterval)
			this.is_open_socket = true;
			this.start();
			// 只有连接正常打开中 ，才能正常收到消息
			this.socketTask.onMessage((res) => {
				console.log(res.data) 
				this.messageData(res.data);
			});
		})
		// 因为如果服务器关闭后，和下面的onclose方法一起发起重连操作，这样会导致重复连接
		// uni.onSocketError((res) => {
		// 	console.log('WebSocket连接打开失败，请检查！');
		// 	this.is_open_socket = false;
		// 	this.reconnect();
		// });
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			console.log("已经被关闭了") 
			this.is_open_socket = false;
			this.reconnect();
		})
	}

	//发送消息
	send(value) {
		// 只有连接正常打开中 ，才能正常成功发送消息
		this.socketTask.send({
			data: value,
			async success() {
				console.log("消息发送成功"); 
			},
 
		});
	}
	//开启心跳检测setInterval
	start() {
		this.heartbeatInterval = setInterval(() => {
			this.data = {
				toId: uni.getStorageSync('uuId'),
				type: '2000', //区分群聊或一对一聊天等
			};
			console.log(this.data)
			this.send(JSON.stringify(this.data));
		}, this.timeout)
	}
	//重新连接
	reconnect() {
		//停止发送心跳 
		clearInterval(this.heartbeatInterval) 
		//如果不是人为关闭的话，进行重连
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				this.connectSocketInit();
			}, 3000)
		}
	}
	//消息处理方法
	messageData(msg) {
		this.msgData = JSON.parse(msg);
		if(this.msgData.type.localeCompare("2000") == 0){
			console.log("后端发来心跳") 
		}
		if(this.msgData.type.localeCompare("TYPE_ADD") == 0 || this.msgData.type.localeCompare("TYPE_ADD_ACCEPTED") == 0){
			uni.$emit('setData', msg)
			getApp().globalData.addUserList.push(this.msgData)
			// uni.setStorage({
			// 	key:'addUser'+uni.getStorageSync('uuId'),
			// 	data:getApp().globalData.addUserList, 
			// })
			uni.$emit('addUser', msg)
			console.log(getApp().globalData.addUserList)
		}
		if(this.msgData.type.localeCompare("TYPE_ONE") == 0 || this.msgData.type.localeCompare("TYPE_GROUP") == 0){
			uni.$emit('setData', msg)
			getApp().globalData.chatList.push(this.msgData);
			//消息更新，异步缓存
			uni.setStorage({
				key:'chatList'+uni.getStorageSync('uuId'),
				data:getApp().globalData.chatList, 
			})
			// uni.setStorageSync('chatList'+uni.getStorageSync('uuId'),getApp().globalData.chatList)
			// console.log(JSON.stringify(uni.getStorageSync('chatList'+uni.getStorageSync('uuId')))+"--------");
			uni.$emit('chatList', msg)
			if(this.msgData.type.localeCompare("TYPE_ONE") == 0){
				uni.$emit('privateChat'+this.msgData.fromId, msg) 
				// Vue.set(getApp().globalData.chatList.privateChat, 'userChat' + this.msgData.fromId, "sfdf");
				// // getApp().globalData.chatList.privateChat.('userChat' + msg.toId).push(this.msgData)
				// getApp().globalData.chatList.privateChat.push(this.msgData)
			}
			if(this.msgData.type.localeCompare("TYPE_GROUP") == 0){
				
			}
		}
	}
	unreadData(){
		sendRequest({
			url: "/message/list",
			method: 'GET',
			data: {uuId:uni.getStorageSync('uuId')},
			success: (res) => {
				var unreadList = res.data.records;
				if(unreadList.length != 0){
					for(let i=0;i<unreadList.length;i++){
						// console.log(unreadList[i])
						this.messageData(JSON.stringify(unreadList[i]));
					}
				}
			}
		});
	}
}

module.exports = websocketUtil
